package com.pinyoumei.app.activity;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.pinyoumei.app.R;
import com.pinyoumei.app.bean.BaseBean;
import com.pinyoumei.app.network.Constants;
import com.pinyoumei.app.utils.SignatureUtils;
import com.pinyoumei.app.utils.ToastUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2021-08-06.
 * --------- 日期 ------- 维护人 ------------ 变更内容 --------
 * 2021-08-06        Administrator             新增Person类
 * 2021-08-06        Administrator             增加sex属性
 * 忘记密码
 */
public class ForgetPassWordActivity extends BaseActivity implements View.OnClickListener {

    private TimeCount timeCount;
    private boolean is_eye = false;
    private ImageView iv_eye;
    private EditText et_phone;
    private EditText et_code;
    private EditText et_password;
    private Button bt_register;
    private TextView tv_code;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forgetpsd);

        InitWidget();


    }


    private void InitWidget() {
        ImageView iv_back = findViewById(R.id.iv_back);
        iv_back.setOnClickListener(this);

        RelativeLayout rl_code = findViewById(R.id.rl_code);
        rl_code.setOnClickListener(this);

        bt_register = findViewById(R.id.bt_register);
        bt_register.setOnClickListener(this);

        tv_code = findViewById(R.id.tv_code);
        iv_eye = findViewById(R.id.iv_eye);
        et_phone = findViewById(R.id.et_phone);
        et_code = findViewById(R.id.et_code);
        et_password = findViewById(R.id.et_password);

        TextChange textChange=new TextChange();
        et_phone.addTextChangedListener(textChange);
        et_code.addTextChangedListener(textChange);
        et_password.addTextChangedListener(textChange);

    }


    //EditText的监听器
    class TextChange implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if(et_phone.length()>0&&
                    et_code.length()>0&&
                    et_password.length()>0){
                bt_register.setBackground(ContextCompat.getDrawable(ForgetPassWordActivity.this,R.drawable.shanpe_green_5dp));

            }else{
                bt_register.setBackground(ContextCompat.getDrawable(ForgetPassWordActivity.this,R.drawable.shanpe_gray_green_5dp));


            }
        }
    }

    //定时器类
    class TimeCount extends CountDownTimer {
        //构造方法
        public TimeCount(long millisInFuture, long countDownInterval){
            super(millisInFuture, countDownInterval);
        }
        @Override
        public void onTick(long millisUntilFinished){
            com.pinyoumei.app.utils.LogUtils.d("log",millisUntilFinished+"");
            tv_code.setText((millisUntilFinished/1000)+"秒");
        }
        @Override
        public void onFinish(){
            tv_code.setText("重新获取");
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.rl_code:
                //验证码

                String phones = et_phone.getText().toString().trim();
                if (!TextUtils.isEmpty(phones)){
                    SendCode(phones,2);
                }else{
                    ToastUtils.showShort("请输入手机号");
                }


                break;


            case R.id.rl_eye:
                if (is_eye) {
                    is_eye = false;
                    iv_eye.setImageResource(R.mipmap.ic_close_eye);
                    //否则隐藏密码
                    et_password.setTransformationMethod(PasswordTransformationMethod.getInstance());
                } else {

                    is_eye = true;
                    iv_eye.setImageResource(R.mipmap.ic_open_eye);
                    //如果选中，显示密码
                    et_password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                }
                break;
            case R.id.bt_register:
                String phone = et_phone.getText().toString().trim();
                String code = et_code.getText().toString().trim();
                String password = et_password.getText().toString().trim();

                if (TextUtils.isEmpty(phone)){
                    Toast.makeText(ForgetPassWordActivity.this, "请输入手机号", Toast.LENGTH_SHORT).show();
                }else if (TextUtils.isEmpty(code)){
                    Toast.makeText(ForgetPassWordActivity.this, "请输入验证码", Toast.LENGTH_SHORT).show();
                }else  if (TextUtils.isEmpty(password)){
                    Toast.makeText(ForgetPassWordActivity.this, "请设置密码（6位或以上）", Toast.LENGTH_SHORT).show();
                }else {
                    SetPsw(phone,password,code);
                }

                break;
        }
    }



    @Override
    protected void onDestroy(){
        if (timeCount != null) {
            timeCount.cancel();
        }
        super.onDestroy();
    }


    private void SendCode(String phone,int type) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_phone", phone);
        map.put("type", type);

        OkGo.<String>post(Constants.SendMSG)
                .params("user_phone", phone)
                .params("type", type)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {


                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        setData(response);
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();
                        BaseBean codeBean = gson.fromJson(response.body(), BaseBean.class);

                        if (codeBean.getCode() >= 0) {

                            if (timeCount == null) {
                                timeCount = new TimeCount(60 * 1000, 1000);//5s的一个定时器 间隔是1s
                                timeCount.start();
                            }

                            Toast.makeText(ForgetPassWordActivity.this, codeBean.getMsg(), Toast.LENGTH_SHORT).show();

                        } else {
                            Toast.makeText(ForgetPassWordActivity.this, codeBean.getMsg(), Toast.LENGTH_SHORT).show();
                        }

                    }

                });
    }


    private void SetPsw(String user_phone,String user_pwd,String verify_code) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_phone", user_phone);
        map.put("user_pwd", user_pwd);
        map.put("verify_code", verify_code);

        OkGo.<String>post(Constants.FORGETPWD)
                .params("user_phone", user_phone)
                .params("user_pwd", user_pwd)
                .params("verify_code", verify_code)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {


                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        setData(response);
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();
                        BaseBean codeBean = gson.fromJson(response.body(), BaseBean.class);

                        if (codeBean.getCode() >= 0) {

                            Toast.makeText(ForgetPassWordActivity.this, codeBean.getMsg(), Toast.LENGTH_SHORT).show();
                            finish();
                        } else {
                            Toast.makeText(ForgetPassWordActivity.this, codeBean.getMsg(), Toast.LENGTH_SHORT).show();
                        }

                    }

                });
    }
}
